﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace SRB.Tg.Operate
{
   public class WriteLogs
    {
        //数据库存操作
        //////SqlDbHelper db = new SqlDbHelper();
        String filePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "logs\\";

        //记录操作日志
        public void writeLogs(String coent, String prefix)
        {
            try
            {
                if(string.IsNullOrWhiteSpace(filePath))
                   filePath = System.AppDomain.CurrentDomain.BaseDirectory + "logs\\";
                //创建文件夹
                creatFolder(filePath);
                //定义文件名，按每天一个文件
                String fileName = prefix + "-" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
                //判断文件是否存在，如果无则创建
                if (!File.Exists(filePath + fileName) == true)
                {
                    FileStream fs = new FileStream(filePath + fileName, FileMode.Create);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff") + "]  " + coent + "\n");
                    sw.Close();
                    fs.Close();
                }
                else
                {
                    StreamWriter sw = File.AppendText(filePath + fileName);
                    sw.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff") + "]  " + coent + "\n");
                    sw.Flush();
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }

        //创建文件夹
        public void creatFolder(String path)
        {
            //不存在 则创建
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

        //移动文件
        public void moveFile(String oldFileDir, String newFileDir, String fileName)
        {
            //如果目录不存在，则创建目录
            creatFolder(oldFileDir); //旧目录
            creatFolder(newFileDir); //新目录
            //将本地文件由原目录移动到新目录
            FileInfo file = new FileInfo(oldFileDir + fileName);
            if (file.Exists)
            {
                //如果目录文件夹中存在同名文件，先删除，后移动
                FileInfo newfile = new FileInfo(newFileDir + fileName);
                if (newfile.Exists)
                {
                    newfile.Delete();//先删除
                }
                //移动文件
                file.MoveTo(newFileDir + fileName); //将文件移动到新目录
            }
        }

        #region 记录最近的一次开关机
        /// <summary>
        /// 通过WIN 日志查出最近时间的开关机时间；
        /// </summary>
        public void readWindowsPowerOnAndShutdownTime()
        {
            EventLog myNewLog = new EventLog();

            myNewLog.Log = "System";
            EventLogEntryCollection myCollection = myNewLog.Entries;

            //掉电不会记录关机时间
            //foreach (EventLogEntry test in myCollection)
            int Count = myCollection.Count; //记录的长度

            for (int j = 0; j < Count; j++)
            {
                EventLogEntry MyEntry_End = myCollection[Count - j - 1];
                if (MyEntry_End.EventID.ToString() == "6006")
                {
                    writeLogs("最近一次关机时间（参考）为：" + MyEntry_End.TimeGenerated, "logs");
                    break;
                }
            }

            for (int i = 0; i < Count; i++)
            {
                EventLogEntry MyEntry = myCollection[Count - i - 1];
                if (MyEntry.EventID.ToString() == "6005")
                //if (MyEntry.InstanceId.ToString() == "6005")
                {
                    writeLogs("最近一次开机时间（参考）为：" + MyEntry.TimeGenerated, "logs");
                    break;
                }
            }


        }
        #endregion
    }
}
